@{
    ViewData["Title"] = "不良品项";
}

@section Styles {
    <link rel="stylesheet" href="~/css/defective.css">
    <style>
        /* 弹窗层级与遮罩（使用Layui默认层级，确保可点击） */
        .layui-layer-shade,
        .layui-layer-shade[layui-layer-shade] {
            /* 仅调整颜色，不强制display，避免始终显示遮罩 */
            background: rgba(0, 0, 0, 0.35);
            z-index: 19891018 !important; /* 小于弹窗本身 */
            pointer-events: auto; /* 允许点击遮罩关闭，不影响弹窗 */
        }
        /* 确保各种类型的弹窗层级都在遮罩之上 */
        .layui-layer,
        .layui-layer.layui-layer-page,
        .layui-layer.layui-layer-iframe,
        .layui-layer.layui-layer-dialog,
        .layui-layer.layui-layer-open {
            z-index: 19891020 !important;
        }
        /* 重置全局按钮与表单的z-index，避免盖住弹窗 */
        .layui-btn { z-index: auto !important; }
        .layui-form-item input,
        .layui-form-item select,
        .layui-form-item button { z-index: auto !important; }

        /* 页面整体样式优化 */
        .layui-fluid {
            padding: 20px;
            background-color: #f5f5f5;
        }

        /* 卡片样式优化 */
        .layui-card {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: none;
        }

        .layui-card-body {
            background-color: white;
        }

        /* 表格样式优化 */
        .layui-table {
            border-radius: 6px;
            overflow: hidden;
        }

        .layui-table thead tr {
            background-color: #fafafa;
        }

        .layui-table tbody tr:hover {
            background-color: #f8f9fa;
        }

        /* 表格列宽优化 */
        #defectiveTable th:nth-child(1), #defectiveTable td:nth-child(1) { width: 50px; min-width: 50px; max-width: 50px; }
        #defectiveTable th:nth-child(2), #defectiveTable td:nth-child(2) { width: 120px; min-width: 120px; max-width: 120px; }
        #defectiveTable th:nth-child(3), #defectiveTable td:nth-child(3) { width: 180px; min-width: 180px; max-width: 180px; }
        #defectiveTable th:nth-child(4), #defectiveTable td:nth-child(4) { width: 100px; min-width: 100px; max-width: 100px; }
        #defectiveTable th:nth-child(5), #defectiveTable td:nth-child(5) { width: 80px; min-width: 80px; max-width: 80px; }
        #defectiveTable th:nth-child(6), #defectiveTable td:nth-child(6) { width: 140px; min-width: 140px; max-width: 140px; }
        #defectiveTable th:nth-child(7), #defectiveTable td:nth-child(7) { width: 100px; min-width: 100px; max-width: 100px; }
        #defectiveTable th:nth-child(8), #defectiveTable td:nth-child(8) { width: 100px; min-width: 100px; max-width: 100px; }

        /* 文本溢出处理 */
        #defectiveTable td {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* 按钮样式优化 */
        .layui-btn {
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .layui-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* 输入框样式优化 */
        .layui-input {
            border-radius: 6px;
            border: 1px solid #e6e6e6;
            transition: border-color 0.3s ease;
        }

        .layui-input:focus {
            border-color: #1E9FFF;
            box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.2);
        }

        /* 搜索区域样式优化 */
        .search-container {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            border-radius: 8px;
            padding: 20px;
            border: 1px solid #e9ecef;
        }

        .search-input-group {
            background: white;
            border-radius: 6px;
            padding: 8px 12px;
            border: 1px solid #e9ecef;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .search-label {
            color: #495057;
            font-weight: 600;
        }

        .search-buttons .layui-btn {
            transition: all 0.3s ease;
        }

        .search-buttons .layui-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* 导入模态框按钮状态样式 */
        .layui-btn-disabled {
            opacity: 0.5 !important;
            cursor: not-allowed !important;
            background-color: #f5f5f5 !important;
            color: #999 !important;
            border-color: #e6e6e6 !important;
            pointer-events: none !important;
        }

        .layui-btn-disabled:hover {
            transform: none !important;
            box-shadow: none !important;
        }

        /* 导入模态框特定按钮样式 */
        #selectFileBtn.layui-btn-disabled,
        #importBtn.layui-btn-disabled {
            opacity: 0.4 !important;
            background-color: #f0f0f0 !important;
            color: #ccc !important;
            border-color: #ddd !important;
            cursor: not-allowed !important;
            pointer-events: none !important;
        }

        #selectFileBtn.layui-btn-disabled:hover,
        #importBtn.layui-btn-disabled:hover {
            transform: none !important;
            box-shadow: none !important;
            background-color: #f0f0f0 !important;
        }
        
        /* 确保启用状态的按钮样式能够覆盖禁用状态 */
        #selectFileBtn:not(.layui-btn-disabled),
        #importBtn:not(.layui-btn-disabled) {
            opacity: 1 !important;
            pointer-events: auto !important;
            cursor: pointer !important;
        }
        
        #selectFileBtn:not(.layui-btn-disabled):not(:disabled),
        #importBtn:not(.layui-btn-disabled):not(:disabled) {
            background-color: #1E9FFF !important;
            color: #fff !important;
            border-color: #1E9FFF !important;
        }
        
        /* 操作按钮禁用状态样式 */
        #editBtn.layui-btn-disabled,
        #deleteBtn.layui-btn-disabled {
            opacity: 0.5;
            cursor: not-allowed !important;
            background-color: #f5f5f5 !important;
            color: #999 !important;
            border-color: #e6e6e6 !important;
            pointer-events: none;
        }

        #editBtn.layui-btn-disabled:hover,
        #deleteBtn.layui-btn-disabled:hover {
            transform: none !important;
            box-shadow: none !important;
        }

        #templateRequiredTip {
            animation: pulse 2s infinite;
        }

        @@keyframes pulse {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0.7;
            }

            100% {
                opacity: 1;
            }
        }

        /* 分页样式优化 */
        #defectivePager {
            margin-top: 10px;
        }

        /* 响应式优化 */
        @@media (max-width: 768px) {
            .layui-fluid {
                padding: 10px;
            }

            .layui-card-body {
                padding: 15px !important;
            }
        }
    </style>
}

<div class="layui-fluid">
    <!-- 页面标题 -->
    <div class="layui-row layui-col-space15" style="margin-bottom: 25px;">
        <div class="layui-col-md12">
            <h2 class="layui-text" style="margin: 0; padding: 15px 0; font-size: 24px; color: #333;">不良品项</h2>
        </div>
    </div>

    <!-- 搜索区域 -->
    <div class="layui-row layui-col-space15" style="margin-bottom: 25px;">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 25px;">
                    <form class="layui-form">
                        <div class="search-container"
                            style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
                            <!-- 搜索输入框 -->
                            <div class="search-input-group"
                                style="display: flex; align-items: center; min-width: 320px;">
                                <label class="search-label"
                                    style="margin: 0 12px 0 0; color: #333; font-weight: 500; white-space: nowrap; font-size: 14px;">不良品项编号：</label>
                                <input type="text" class="layui-input" id="defectiveCode" placeholder="请输入不良品项编号"
                                    style="height: 36px; line-height: 36px; border-radius: 6px; border: 1px solid #e6e6e6; padding: 0 12px; min-width: 220px; flex: 1;">
                            </div>

                            <!-- 搜索按钮组 -->
                            <div class="search-buttons" style="display: flex; align-items: center; gap: 12px;">
                                <button type="button" class="layui-btn layui-btn-primary" onclick="searchData()" style="height: 36px; line-height: 36px; padding: 0 20px; border-radius: 6px; font-weight: 500; min-width: 80px;">
                                            <i class="layui-icon layui-icon-search"></i> 查询
                                    </button>
                                <button type="button" class="layui-btn" onclick="resetSearch()" style="height: 36px; line-height: 36px; padding: 0 20px; border-radius: 6px; font-weight: 500; min-width: 80px;">
                                           <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                <button type="button" class="layui-btn layui-btn-normal" onclick="showAdvancedSearch()" style="height: 36px; line-height: 36px; padding: 0 20px; border-radius: 6px; font-weight: 500; min-width: 100px;">
                                            <i class="layui-icon layui-icon-filter"></i> 高级查询
                                    </button>
                                </div>
                            
                            <!-- 设置按钮 -->
                            <div class="settings-button" style="margin-left: auto;">
                                <button type="button" class="layui-btn layui-btn-warm" onclick="showColumnSettings()" style="height: 36px; line-height: 36px; padding: 0 20px; border-radius: 6px; font-weight: 500; min-width: 80px;">
                                            <i class="layui-icon layui-icon-set"></i> 设置
                                        </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="layui-row layui-col-space15" style="margin-bottom: 25px;">
        <div class="layui-col-md12">
                         <div style="display: flex; gap: 12px; flex-wrap: nowrap; overflow-x: auto;">
                                 <button type="button" class="layui-btn layui-btn-normal" style="background-color: #5FB878; padding: 8px 16px; height: 36px; line-height: 20px; white-space: nowrap; flex-shrink: 0;" onclick="createNew()">
                <i class="layui-icon layui-icon-add-1"></i> 新建
            </button>
                 <button type="button" class="layui-btn layui-btn-primary" style="background-color: #1E9FFF; padding: 8px 16px; height: 36px; line-height: 20px; white-space: nowrap; flex-shrink: 0;" onclick="editSelected()" disabled id="editBtn">
                <i class="layui-icon layui-icon-edit"></i> 编辑
            </button>
                 <button type="button" class="layui-btn layui-btn-danger" style="padding: 8px 16px; height: 36px; line-height: 20px; white-space: nowrap; flex-shrink: 0;" onclick="deleteSelected()" disabled id="deleteBtn">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </button>
                 <button type="button" class="layui-btn layui-btn-normal" style="background-color: #FFFFFF; color: #333333; border: 1px solid #E6E6E6; padding: 8px 16px; height: 36px; line-height: 20px; white-space: nowrap; flex-shrink: 0;" onclick="importData()">
                <i class="layui-icon layui-icon-upload"></i> 导入
            </button>
                 <button type="button" class="layui-btn layui-btn-normal" style="background-color: #FFFFFF; color: #333333; border: 1px solid #E6E6E6; padding: 8px 16px; height: 36px; line-height: 20px; white-space: nowrap; flex-shrink: 0;" onclick="exportData()">
                <i class="layui-icon layui-icon-download-circle"></i> 导出
            </button>
            </div>
        </div>
    </div>

    <!-- 操作提示 -->
    <div class="layui-row" style="margin: -10px 0 10px 0;">
        <div class="layui-col-md12">
            <div id="selectionHint" style="display: block; background: #FFFBE6; border: 1px solid #FFE58F; color: #ad6800; padding: 8px 12px; border-radius: 4px;">
                <i class="layui-icon layui-icon-tips" style="margin-right:6px;"></i>请先选择要编辑或删除的行
            </div>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-row layui-col-space15" style="margin-bottom: 25px;">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 20px; overflow-x: auto;">
                    <table class="layui-table" id="defectiveTable" style="margin: 0; min-width: 1200px; width: 100%;">
                        <thead>
                            <tr>
                                <th style="padding: 15px 8px; text-align: center; width: 60px;">
                                    <input type="checkbox" id="selectAll" lay-skin="primary" onchange="toggleSelectAll()">
                                    </th>
                                <th style="padding: 15px 12px; text-align: center; width: 150px;" onclick="sortTable('defectiveCode')">
                                    不良品项编号 <i class="layui-icon layui-icon-sort"></i>
                                    </th>
                                <th style="padding: 15px 12px; text-align: center; width: 200px;" onclick="sortTable('defectiveName')">
                                    不良品项名称 <i class="layui-icon layui-icon-sort"></i>
                                    </th>
                                <th style="padding: 15px 12px; text-align: center; width: 120px;">附件</th>
                                <th style="padding: 15px 12px; text-align: center; width: 100px;">图片</th>
                                <th style="padding: 15px 12px; text-align: center; width: 160px;"
                                    onclick="sortTable('createTime')">
                                    创建时间 <i class="layui-icon layui-icon-sort"></i>
                                    </th>
                                <th style="padding: 15px 12px; text-align: center; width: 120px;">创建人</th>
                                <th style="padding: 15px 12px; text-align: center; width: 120px;">修改人</th>
                                </tr>
                            </thead>
                            <tbody id="defectiveTableBody">
                                <!-- 数据行将通过JavaScript动态生成 -->
                            </tbody>
                        </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 分页控件 -->
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 20px; text-align: center;">
                    <div id="defectivePager"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 导入数据模态框 -->
<div id="importModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 25px;">
            <div class="layui-form">
                <!-- 步骤说明 -->
                <div class="layui-form-item" style="margin-bottom: 25px;">
                    <div class="layui-text" style="color: #666; line-height: 1.6;">
                        <h4 style="color: #333; margin-bottom: 15px;">导入步骤说明：</h4>
                        <p>1. 下载Excel模板文件</p>
                        <p>2. 按照模板格式填写数据</p>
                        <p>3. 选择填写好的Excel文件</p>
                        <p>4. 点击导入按钮完成数据导入</p>
                    </div>
                </div>

                <!-- 下载模板 -->
                <div class="layui-form-item" style="margin-bottom: 25px;">
                    <label class="layui-form-label" style="width: 120px;">下载模板</label>
                    <div class="layui-input-block" style="margin-left: 120px;">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="downloadTemplate()"
                            style="height: 36px; line-height: 36px; padding: 0 20px;">
                            <i class="layui-icon layui-icon-download"></i> 下载Excel模板
                        </button>
                        <div class="layui-text" style="margin-top: 8px; color: #999; font-size: 12px;">
                            点击下载标准Excel模板，按照模板格式填写数据
                        </div>
                    </div>
                </div>

                <!-- 选择文件 -->
                <div class="layui-form-item" style="margin-bottom: 25px;">
                    <label class="layui-form-label" style="width: 120px;">选择文件</label>
                    <div class="layui-input-block" style="margin-left: 120px;">
                        <input type="file" id="importFile" accept=".xlsx,.xls" style="display: none;" onchange="handleImportFileSelect(this)">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-disabled" id="selectFileBtn" onclick="document.getElementById('importFile').click()" disabled style="height: 36px; line-height: 36px; padding: 0 20px;">
                            <i class="layui-icon layui-icon-upload"></i> 选择Excel文件
                        </button>
                        <div id="selectedFileName" class="layui-text"
                            style="margin-top: 8px; color: #666; display: none;">
                            已选择文件：<span id="fileNameText"></span>
                        </div>
                        <div class="layui-text" style="margin-top: 8px; color: #ff6b6b; font-size: 12px;" id="templateRequiredTip">
                            ⚠️ 请先下载模板文件
                        </div>
                    </div>
                </div>

                <!-- 导入按钮 -->
                <div class="layui-form-item" style="margin-bottom: 0;">
                    <label class="layui-form-label" style="width: 120px;">执行导入</label>
                    <div class="layui-input-block" style="margin-left: 120px;">
                        <button type="button" class="layui-btn layui-btn-normal layui-btn-disabled" id="importBtn" onclick="executeImport()" disabled style="height: 36px; line-height: 36px; padding: 0 20px;">
                            <i class="layui-icon layui-icon-ok"></i> 开始导入
                        </button>
                        <div class="layui-text" style="margin-top: 8px; color: #999; font-size: 12px;">
                            请先下载模板并选择文件
                        </div>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-warm" onclick="enableImportButton()" style="margin-top: 8px; display: none;" id="debugEnableBtn">
                            调试：强制启用
                        </button>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="debugImportModal()" style="margin-left: 5px; margin-top: 8px; display: none;" id="debugInfoBtn">
                            调试：查看状态
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 高级查询模态框 -->
<div id="advancedSearchModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" id="advancedSearchForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项编号</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="advDefectiveCode" placeholder="请输入不良品项编号">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项名称</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="advDefectiveName" placeholder="请输入不良品项名称">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">每页显示数量</label>
                    <div class="layui-input-block">
                        <select class="layui-select" id="advPageSize">
                            <option value="10" selected>10条/页</option>
                            <option value="20">20条/页</option>
                            <option value="30">30条/页</option>
                            <option value="50">50条/页</option>
                            <option value="100">100条/页</option>
                        </select>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 列设置模态框 -->
<div id="columnSettingsModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3><i class="layui-icon layui-icon-about"></i> 设置</h3>
        </div>
        <div class="layui-card-body">
            <!-- 说明横幅 -->
            <div class="layui-bg-green" style="padding: 10px; margin-bottom: 15px; border-radius: 4px;">
                <i class="layui-icon layui-icon-info"></i>
                拖动列名可调整表格列显示顺序
                <i class="layui-icon layui-icon-close" style="float: right; cursor: pointer;"
                    onclick="hideInstruction()"></i>
            </div>

            <!-- 列配置表格 -->
            <table class="layui-table" id="columnSettingsTable">
                <thead>
                    <tr>
                        <th width="50">#</th>
                        <th>列名</th>
                        <th width="100">是否显示</th>
                    </tr>
                </thead>
                <tbody id="columnSettingsBody">
                    <!-- 列配置行将通过JavaScript动态生成 -->
                </tbody>
            </table>

            <!-- 操作按钮 -->
            <div class="layui-form-item" style="margin-top: 20px;">
                <div class="layui-input-block">
                    <button type="button" id="btnColumnCancel" class="layui-btn layui-btn-primary" onclick="cancelColumnSettings()">
                        <i class="layui-icon layui-icon-close"></i> 取消
                    </button>
                    <button type="button" id="btnColumnReset" class="layui-btn layui-btn-normal" onclick="resetColumnSettings()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button type="button" id="btnColumnConfirm" class="layui-btn layui-btn-primary" onclick="confirmColumnSettings()">
                        <i class="layui-icon layui-icon-ok"></i> 确定
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增不良品模态框 -->
<div id="addDefectiveModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" id="addDefectiveForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项编号</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="addDefectiveCode" placeholder="请输入，忽略将自动生成" required>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项名称</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="addDefectiveName" placeholder="请输入不良品项名称" required>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">附件</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <div class="layui-upload-list">
                                <div class="layui-upload-preview" id="attachmentPreview" style="display: none;">
                                    <div class="layui-upload-file-info">
                                        <i class="layui-icon layui-icon-file"></i>
                                        <span class="file-name"></span>
                                        <div class="layui-upload-remove" onclick="removeAttachment()"
                                            style="cursor: pointer;">
                                            <i class="layui-icon layui-icon-close"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-upload-placeholder" id="attachmentPlaceholder">
                                    <div class="layui-upload-area attachment-area" onclick="triggerAttachmentUpload()">
                                        <i class="layui-icon layui-icon-upload"
                                            style="font-size: 48px; color: #c2c2c2;"></i>
                                        <p style="margin-top: 10px; color: #999;">点击或拖拽文件到此处上传</p>
                                        <p style="font-size: 12px; color: #ccc;">支持PDF、Word、Excel、TXT等格式</p>
                        </div>
                            </div>
                        </div>
                            <input type="file" class="layui-input" id="addAttachmentFile" accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar" style="display: none;" onchange="handleAttachmentSelect(this)">
                        <input type="hidden" id="addAttachmentUrl" name="attachmentUrl">
                    </div>
                            </div>
                        </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">图片</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <div class="layui-upload-list">
                                <div class="layui-upload-preview" id="imagePreview" style="display: none;">
                                    <img src="" alt="图片预览"
                                        style="max-width: 200px; max-height: 200px; border-radius: 4px;">
                                    <div class="layui-remove" onclick="removeImage()" style="cursor: pointer;">
                                        <i class="layui-icon layui-icon-close"></i>
                                    </div>
                                </div>
                                <div class="layui-upload-placeholder" id="imagePlaceholder">
                                    <div class="layui-upload-area" onclick="triggerImageUpload()">
                                        <i class="layui-icon layui-icon-picture"
                                            style="font-size: 48px; color: #c2c2c2;"></i>
                                        <p style="margin-top: 10px; color: #999;">点击或拖拽图片到此处上传</p>
                                        <p style="font-size: 12px; color: #ccc;">支持JPG、PNG、GIF等图片格式</p>
                                    </div>
                                </div>
                            </div>
                            <input type="file" class="layui-input" id="addImageFile" accept="image/*"
                                style="display: none;" onchange="handleImageSelect(this)">
                            <!-- 隐藏字段存储图片URL -->
                            <input type="hidden" id="addImageUrl" name="imageUrl">
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑不良品模态框 -->
<div id="editDefectiveModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" id="editDefectiveForm">
                <input type="hidden" id="editDefectiveId">

                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项编号</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="editDefectiveCode" placeholder="请输入不良品项编号" required>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项名称</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="editDefectiveName" placeholder="请输入不良品项名称" required>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">附件</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <div class="layui-upload-list">
                                <div class="layui-upload-preview" id="editAttachmentPreview" style="display: none;">
                                    <div class="layui-upload-file-info">
                                        <i class="layui-icon layui-icon-file"></i>
                                        <span class="file-name"></span>
                                        <div class="layui-upload-remove" onclick="removeEditAttachment()"
                                            style="cursor: pointer;">
                                            <i class="layui-icon layui-icon-close"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-upload-placeholder" id="editAttachmentPlaceholder">
                                    <div class="layui-upload-area attachment-area"
                                        onclick="triggerEditAttachmentUpload()">
                                        <i class="layui-icon layui-icon-upload"
                                            style="font-size: 48px; color: #c2c2c2;"></i>
                                        <p style="margin-top: 10px; color: #999;">点击或拖拽文件到此处上传</p>
                                        <p style="font-size: 12px; color: #ccc;">支持PDF、Word、Excel、TXT等格式</p>
                                    </div>
                                </div>
                            </div>
                            <input type="file" class="layui-input" id="editAttachmentFile"
                                accept=".pdf,.doc,.docx,.xls,.xlsx,.txt" style="display: none;"
                                onchange="handleEditAttachmentSelect(this)">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">图片</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <div class="layui-upload-list">
                                <div class="layui-upload-preview" id="editImagePreview" style="display: none;">
                                    <img src="" alt="图片预览"
                                        style="max-width: 200px; max-height: 200px; border-radius: 4px;">
                                    <div class="layui-upload-remove" onclick="removeEditImage()"
                                        style="cursor: pointer;">
                                        <i class="layui-icon layui-icon-close"></i>
                                    </div>
                                </div>
                                <div class="layui-upload-placeholder" id="editImagePlaceholder">
                                    <div class="layui-upload-area" onclick="triggerEditImageUpload()">
                                        <i class="layui-icon layui-icon-picture"
                                            style="font-size: 48px; color: #c2c2c2;"></i>
                                        <p style="margin-top: 10px; color: #999;">点击或拖拽图片到此处上传</p>
                                        <p style="font-size: 12px; color: #ccc;">支持JPG、PNG、GIF等图片格式</p>
                                    </div>
                                </div>
                            </div>
                            <input type="file" class="layui-input" id="editImageFile" accept="image/*"
                                style="display: none;" onchange="handleEditImageSelect(this)">
                            <!-- 隐藏字段存储图片URL -->
                            <input type="hidden" id="editImageUrl" name="editImageUrl">
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;
        let selectedItems = [];

        // 写入API基础地址与图片URL标准化
        const WRITE_API_URL = '@ViewData["WriteApiUrl"]' || 'http://localhost:5090/api';
        const WRITE_API_BASE = WRITE_API_URL.replace(/\/api$/, '');

        function normalizeImageUrl(url) {
            if (!url) return '';
            try {
                // 如果是绝对URL，则替换为写API的主机端口
                if (url.startsWith('http://') || url.startsWith('https://')) {
                    const u = new URL(url);
                    const base = new URL(WRITE_API_BASE);
                    // 仅当路径以 /Upload 开头（静态文件）时进行主机替换
                    if (u.pathname.toLowerCase().startsWith('/upload')) {
                        u.protocol = base.protocol;
                        u.hostname = base.hostname;
                        u.port = base.port;
                        return u.toString();
                    }
                    return url;
                }
                // 相对路径，补全为写API基础地址
                if (url.startsWith('/')) return WRITE_API_BASE + url;
                return WRITE_API_BASE + '/' + url;
            } catch (e) {
                return url;
            }
        }

        // 渲染附件超链接（点击在新标签在线预览，无法在线预览时直接下载）
        function renderAttachmentLink(path) {
            if (!path) return '';
            const url = normalizeImageUrl(path);
            const fileName = (path.split('/').pop() || '').trim();
            return `<a href="${url}" target="_blank" rel="noopener" style="color:#1E9FFF; text-decoration:none;" onclick="return previewAttachment(event, '${encodeURIComponent(url)}');">${fileName || url}</a>`;
        }

        // 预览附件（优先内嵌预览，失败则新开标签直接访问）
        function previewAttachment(e, encodedUrl) {
            try {
                e && e.preventDefault();
                const url = decodeURIComponent(encodedUrl);
                const lower = url.toLowerCase();
                const isImage = lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.jpeg') || lower.endsWith('.gif') || lower.endsWith('.webp');
                const isPdf = lower.endsWith('.pdf');
                const isText = lower.endsWith('.txt');
                const isOffice = lower.endsWith('.doc') || lower.endsWith('.docx') || lower.endsWith('.xls') || lower.endsWith('.xlsx') || lower.endsWith('.ppt') || lower.endsWith('.pptx');

                // 构造可预览的地址
                let previewUrl = url;
                if (isOffice) {
                    // 使用微软在线预览（需公网可访问），本地同域环境也可尝试
                    previewUrl = `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(url)}`;
                }

                // 弹窗内嵌预览
                let contentHtml = '';
                if (isImage) {
                    contentHtml = `<div style=\"padding:10px;text-align:center\"><img src=\"${url}\" style=\"max-width:100%;max-height:80vh\"/></div>`;
                } else if (isPdf) {
                    contentHtml = `<iframe src=\"${url}\" style=\"width:100%;height:80vh;border:0\"></iframe>`;
                } else if (isText) {
                    contentHtml = `<iframe src=\"${url}\" style=\"width:100%;height:80vh;border:0\"></iframe>`;
                } else if (isOffice) {
                    contentHtml = `<iframe src=\"${previewUrl}\" style=\"width:100%;height:80vh;border:0\"></iframe>`;
                } else {
                    // 其他类型直接在新标签打开
                    window.open(url, '_blank');
                    return false;
                }

                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.open({
                        type: 1,
                        title: '附件预览',
                        area: ['80%', '85%'],
                        shade: 0,
                        content: contentHtml,
                        btn: ['下载', '关闭'],
                        yes: function(index){ window.open(url, '_blank'); },
                        btn2: function(index){ layer.close(index); }
                    });
                });
                return false;
            } catch(err) {
                // 回退：直接打开
                window.open(decodeURIComponent(encodedUrl), '_blank');
                return false;
            }
        }

        // 获取当前新增弹窗的上下文容器（若未打开则回退到document）
        function getAddModalContext() {
            const $visibleContents = $('.layui-layer-content:visible');
            for (let i = $visibleContents.length - 1; i >= 0; i--) {
                const $content = $($visibleContents[i]);
                if ($content.find('#addDefectiveForm').length > 0) {
                    return $content;
                }
            }
            return $(document);
        }

        // 获取当前编辑弹窗的上下文容器（若未打开则回退到document）
        function getEditModalContext() {
            const $visibleContents = $('.layui-layer-content:visible');
            for (let i = $visibleContents.length - 1; i >= 0; i--) {
                const $content = $($visibleContents[i]);
                if ($content.find('#editDefectiveForm').length > 0) {
                    return $content;
                }
            }
            return $(document);
        }

        // 获取当前"设置"弹窗的上下文容器（若未打开则回退到document）
        function getSettingsModalContext() {
            const $visibleContents = $('.layui-layer-content:visible');
            for (let i = $visibleContents.length - 1; i >= 0; i--) {
                const $content = $($visibleContents[i]);
                if ($content.find('#columnSettingsModal').length > 0 || $content.find('#columnSettingsBody').length > 0) {
                    return $content;
                }
            }
            return $(document);
        }

        // 页面加载完成后执行
        $(document).ready(function () {
            // 初始化Layui表单和分页
            layui.use(['form', 'element', 'laypage'], function () {
                var form = layui.form;
                var element = layui.element;
                var laypage = layui.laypage;

                // 重新渲染表单
                form.render();

                // 初始化分页
                initPagination(laypage);

                // 初始化图片拖拽上传
                initImageDragAndDrop();

                // 确保按钮初始状态为禁用
                $('#editBtn').prop('disabled', true);
                $('#editBtn').addClass('layui-btn-disabled');
                $('#deleteBtn').prop('disabled', true);
                $('#deleteBtn').addClass('layui-btn-disabled');

                // 加载数据
                loadData();
            });
        });

        // 加载数据
        function loadData() {
            const defectiveCode = $('#defectiveCode').val();

            $.ajax({
                url: '@Url.Action("GetPage", "Defective")',
                type: 'GET',
                data: {
                    defectiveCode: defectiveCode,
                    pageIndex: currentPage,
                    pageSize: pageSize
                },
                success: function (response) {
                    if (response.code === 200) {
                        renderTable(response);
                        updatePagination(response);
                    } else {
                        layui.layer.msg('获取数据失败: ' + (response.msg || '未知错误'), { icon: 2 });
                    }
                },
                error: function () {
                    layui.layer.msg('获取数据失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 渲染表格
        function renderTable(data) {
            const tbody = $('#defectiveTableBody');
            tbody.empty();

            if (data.pageData && data.pageData.length > 0) {
                data.pageData.forEach(function (item) {
                    const imagePath = normalizeImageUrl(item.imagePath);
                    const row = `
                        <tr style="height: 60px;">
                            <td style="padding: 12px 8px; text-align: center; width: 60px;">
                                <input type="checkbox" class="row-checkbox" lay-skin="primary" value="${item.id}" onchange="updateSelectedItems()">
                            </td>
                            <td style="padding: 12px; text-align: center;" title="${item.defectiveCode || ''}">${item.defectiveCode || ''}</td>
                            <td style="padding: 12px; text-align: center;" title="${item.defectiveName || ''}">${item.defectiveName || ''}</td>
                            <td style="padding: 12px; text-align: center;">${renderAttachmentLink(item.attachmentPath)}</td>
                            <td style="padding: 12px; text-align: center;">${imagePath && imagePath !== 'string' ? `<img src="${imagePath}" class="layui-thumb" style="width: 50px; height: 50px; border-radius: 4px;" alt="img" onerror="this.style.display='none'; this.nextElementSibling.style.display='inline';"><i class="layui-icon layui-icon-picture text-muted" style="display: none;"></i>` : '<i class="layui-icon layui-icon-picture text-muted"></i>'}</td>
                            <td style="padding: 12px; text-align: center;">${formatDateTime(item.createTime)}</td>
                            <td style="padding: 12px; text-align: center;">${item.creatorName || ''}</td>
                            <td style="padding: 12px; text-align: center;">${item.modifierName || ''}</td>
                        </tr>
                    `;
                    tbody.append(row);
                });
            } else {
                tbody.append('<tr><td colspan="8" class="layui-text-center" style="text-align: center; color: #999; padding: 40px; font-size: 16px;">暂无数据</td></tr>');
            }

            // 渲染完表格后，初始化按钮状态
            updateSelectedItems();
        }

        // 初始化分页组件
        function initPagination(laypage) {
            laypage.render({
                elem: 'defectivePager',
                count: 0,
                curr: currentPage,
                limit: pageSize,
                limits: [10, 20, 30, 50, 100],
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                jump: function (obj, first) {
                    if (!first) {
                        currentPage = obj.curr;
                        pageSize = obj.limit;
                        loadData();
                    }
                }
            });
        }

        // 更新分页信息
        function updatePagination(data) {
            // 使用Layui分页组件更新分页信息
            const totalCount = data.totaCount || 0;
            const totalPages = data.totaPage || 1;

            // 重新渲染分页组件
            layui.use('laypage', function () {
                var laypage = layui.laypage;
                laypage.render({
                    elem: 'defectivePager',
                    count: totalCount,
                    curr: currentPage,
                    limit: pageSize,
                    limits: [10, 20, 30, 50, 100],
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function (obj, first) {
                        if (!first) {
                            currentPage = obj.curr;
                            pageSize = obj.limit;
                            loadData();
                        }
                    }
                });
            });
        }

        // 搜索数据
        function searchData() {
            currentPage = 1;
            loadData();
        }

        // 重置查询条件
        function resetSearch() {
            // 清空简单查询输入
            $('#defectiveCode').val('');
            // 重置分页
            currentPage = 1;
            // 刷新数据
            loadData();
        }

        // 高级查询
        function showAdvancedSearch() {
            // 显示高级查询模态框
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '高级查询',
                    content: $('#advancedSearchModal').html(),
                    area: ['450px', '350px'],
                    shade: 0,
                    btn: ['查询', '重置', '关闭'],
                    btn1: function (index, layero) {
                        executeAdvancedSearch();
                        layer.close(index);
                    },
                    btn2: function (index, layero) {
                        resetAdvancedSearch();
                        layer.close(index);
                    },
                    btn3: function (index, layero) {
                        layer.close(index);
                    }
                });
            });
        }

        // 执行高级查询
        function executeAdvancedSearch() {
            // 作用域限定到当前弹窗内容，避免读取到隐藏模板
            var $scope = $('.layui-layer-content:visible').last();
            // 获取高级查询参数
            var queryParams = {
                defectiveCode: $scope.find('#advDefectiveCode').val(),
                defectiveName: $scope.find('#advDefectiveName').val(),
                pageIndex: 1,
                pageSize: parseInt($scope.find('#advPageSize').val())
            };

            // 执行高级查询
            executeAdvancedSearchRequest(queryParams);
        }

        // 重置高级查询
        function resetAdvancedSearch() {
            $('#advancedSearchForm')[0].reset();
        }

        // 关闭高级查询
        function closeAdvancedSearch() {
            var layer = layui.layer;
            layer.closeAll();
        }

        // 执行高级查询请求
        function executeAdvancedSearchRequest(queryParams) {
            // 更新分页参数
            pageSize = queryParams.pageSize;
            currentPage = 1;

            $.ajax({
                url: '@Url.Action("GetAdvancedPage", "Defective")',
                type: 'GET',
                data: queryParams,
                success: function (response) {
                    if (response.code === 200) {
                        renderTable(response);
                        updatePagination(response);

                        // 显示查询结果提示
                        showQueryResultTip('高级查询执行成功');
                    } else {
                        layui.layer.msg('高级查询失败: ' + (response.msg || '未知错误'), { icon: 2 });
                    }
                },
                error: function () {
                    layui.layer.msg('高级查询失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 显示查询结果提示
        function showQueryResultTip(message) {
            // 创建提示元素
            var tip = $('<div class="layui-layer layui-layer-msg layui-layer-msg-1" style="position: fixed; top: 20px; right: 20px; z-index: 9999; background-color: #5FB878; color: white; padding: 10px 20px; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.15);">' +
                '<i class="layui-icon layui-icon-ok-circle"></i> ' + message +
                '<i class="layui-icon layui-icon-close" style="margin-left: 10px; cursor: pointer;" onclick="$(this).parent().remove()"></i>' +
                '</div>');

            // 添加到页面
            $('body').append(tip);

            // 3秒后自动消失
            setTimeout(function () {
                tip.remove();
            }, 3000);
        }

        // 新建
        function createNew() {
            // 显示新增不良品模态框
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '新增不良品',
                    content: $('#addDefectiveModal').html(),
                    area: ['500px', '450px'],
                    shade: 0,
                    btn: ['保存', '重置', '取消'],
                    btn1: function (index, layero) {
                        saveNewDefective(index);
                    },
                    btn2: function (index, layero) {
                        resetAddForm();
                    },
                    btn3: function (index, layero) {
                        layer.close(index);
                    },
                    success: function (layero, index) {
                        // 绑定新增模态框的事件
                        bindAddModalEvents();

                        // 重新渲染表单
                        layui.form.render();
                    }
                });
            });
        }

        // 保存新增不良品
        function saveNewDefective(layerIndex) {
            const $scope = getAddModalContext();
            // 获取表单数据
            const defectiveCode = $scope.find('#addDefectiveCode').val().trim();
            const defectiveName = $scope.find('#addDefectiveName').val().trim();
            const attachmentFile = $scope.find('#addAttachmentFile')[0] ? $scope.find('#addAttachmentFile')[0].files[0] : null;
            const imageUrl = $scope.find('#addImageUrl').val(); // 获取图片URL
            const attachmentUrl = $scope.find('#addAttachmentUrl').val(); // 获取附件URL

            // 验证必填字段
            if (!defectiveCode) {
                layui.layer.msg('请输入不良品项编号', { icon: 2 });
                return;
            }
            if (!defectiveName) {
                layui.layer.msg('请输入不良品项名称', { icon: 2 });
                return;
            }

            // 创建FormData对象用于文件上传
            const formData = new FormData();
            formData.append('defectiveCode', defectiveCode);
            formData.append('defectiveName', defectiveName);
            
            // 由前端先上传，保存返回路径
            if (attachmentUrl) {
                formData.append('attachmentPath', attachmentUrl);
            }

            if (imageUrl) {
                formData.append('imagePath', imageUrl);
            }

            // 发送POST请求到WriteApiUrl
            $.ajax({
                url: '@Url.Action("Add", "Defective")',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    if (response.code === 200) {
                        layui.layer.msg('新增成功', { icon: 1 });
                        layui.layer.close(layerIndex);
                        currentPage = 1;
                        loadData();
                        resetAddForm();
                    } else {
                        layui.layer.msg('新增失败: ' + (response.msg || '未知错误'), { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    console.error('新增请求失败:', error);
                    layui.layer.msg('新增失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 重置新增表单
        function resetAddForm() {
            const $scope = getAddModalContext();
            if ($scope.find('#addDefectiveForm')[0]) $scope.find('#addDefectiveForm')[0].reset();
            $scope.find('#addImageUrl').val('');
            $scope.find('#addAttachmentUrl').val('');
            $scope.find('#attachmentPreview').hide();
            $scope.find('#attachmentPlaceholder').show();
            $scope.find('#imagePreview').hide();
            $scope.find('#imagePlaceholder').show();
        }

        // 编辑选中项
        function editSelected() {
            // 双重检查：检查全局变量和DOM状态
            const checkedCheckboxes = $('#defectiveTableBody tr input[type="checkbox"]:checked');
            const actualSelectedCount = checkedCheckboxes.length;

            // 检查是否有选中的行
            if (selectedItems.length === 0 || actualSelectedCount === 0) {
                layui.layer.msg('请选择要编辑的行！', { icon: 2, time: 3000 });

                // 强制更新按钮状态
                updateSelectedItems();
                return;
            }

            // 检查是否只选择了一行
            if (selectedItems.length > 1 || actualSelectedCount > 1) {
                layui.layer.msg('只能选择一个项目进行编辑', { icon: 2, time: 2000 });
                return;
            }

            // 获取选中行的数据
            const selectedId = selectedItems[0];
            const selectedRow = $(`#defectiveTableBody tr input[value="${selectedId}"]`).closest('tr');

            // 验证行数据是否存在
            if (selectedRow.length === 0) {
                layui.layer.msg('无法找到选中的行数据，请重新选择', { icon: 2, time: 2000 });
                return;
            }

            // 提取行数据
            const rowData = {
                id: selectedId,
                defectiveCode: selectedRow.find('td:eq(1)').text().trim(),
                defectiveName: selectedRow.find('td:eq(2)').text().trim(),
                attachmentPath: selectedRow.find('td:eq(3) a').text().trim() || '',
                imagePath: selectedRow.find('td:eq(4) img').attr('src') || ''
            };

            // 验证必要数据
            if (!rowData.defectiveCode && !rowData.defectiveName) {
                layui.layer.msg('选中的行数据不完整，请重新选择', { icon: 2, time: 2000 });
                return;
            }

            // 显示编辑模态框
            showEditModal(rowData);
        }

        // 删除选中项
        function deleteSelected() {
            if (selectedItems.length === 0) {
                layui.layer.msg('请您选择要删除的项目', { icon: 2, time: 2000 });
                return;
            }

            // 确认删除
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.confirm(`确定要删除选中的 ${selectedItems.length} 个项目吗？`, {
                    title: '确认删除',
                    icon: 3,
                    btn: ['确定', '取消']
                }, function (index) {
                    // 用户确认删除
                    executeDelete(selectedItems);
                    layer.close(index);
                });
            });
        }

        // 执行删除操作
        function executeDelete(ids) {
            // 显示加载提示
            const loadingIndex = layui.layer.load(1, {
                shade: 0
            });

            // 发送删除请求
            $.ajax({
                url: '@Url.Action("DeleteBatch", "Defective")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ ids: ids }),
                success: function (response) {
                    layui.layer.close(loadingIndex);

                    if (response.code === 200) {
                        layui.layer.msg('删除成功', { icon: 1 });

                        // 清空选中项
                        selectedItems = [];
                        updateSelectedItems();

                        // 重新加载数据
                        loadData();
                    } else {
                        layui.layer.msg('删除失败: ' + (response.msg || '未知错误'), { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.close(loadingIndex);
                    console.error('删除请求失败:', error);
                    layui.layer.msg('删除失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 导入数据
        function importData() {
            showImportModal();
        }

        // 显示导入弹窗
        function showImportModal() {
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '导入不良品数据',
                    content: $('#importModal').html(),
                    area: ['600px', '500px'],
                    shade: 0,
                    btn: ['关闭'],
                    btn1: function (index, layero) {
                        layer.close(index);
                    },
                    success: function(layero, index) {
                                        // 重置全局状态
                window.templateDownloaded = false;
                window.selectedImportFile = null;
                        
                        // 在模态框上下文中查找元素
                        var $modal = $(layero);
                        var $selectedFileName = $modal.find('#selectedFileName');
                        var $templateRequiredTip = $modal.find('#templateRequiredTip');
                        var $importBtn = $modal.find('#importBtn');
                        var $selectFileBtn = $modal.find('#selectFileBtn');
                        var $importFile = $modal.find('#importFile');
                        
                        // 重置导入状态
                        $selectedFileName.hide();
                        $templateRequiredTip.show();
                        $importBtn.prop('disabled', true).addClass('layui-btn-disabled');
                        $selectFileBtn.prop('disabled', true).addClass('layui-btn-disabled');
                        $importFile.val('');
                        
                        // 重新渲染表单
                        layui.form.render();
                        
                        // 在开发环境中显示调试按钮
                        if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                            $modal.find('#debugEnableBtn').show();
                            $modal.find('#debugInfoBtn').show();
                        }
                        
                        console.log('导入模态框已打开，状态已重置');
                    }
                });
            });
        }

        // 下载导入模板
        function downloadTemplate() {
            // 显示下载中提示
            layui.layer.msg('正在下载模板...', { icon: 16, time: 0 });

            try {
            // 获取WriteApiUrl配置
            var writeApiUrl = '@ViewData["WriteApiUrl"]' || 'http://localhost:5090/api';
            var url = writeApiUrl + '/Defective/DownloadTemplate';
            
            // 创建下载链接
            var link = document.createElement('a');
            link.href = url;
            link.download = '不良品导入模板.xlsx';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 关闭下载提示
            layui.layer.closeAll('loading');
            layui.layer.msg('模板下载完成', {icon: 1});
            
            // 在所有可见的模态框中查找并启用选择文件按钮
            $('.layui-layer-content:visible').each(function() {
                var $modal = $(this);
                var $selectFileBtn = $modal.find('#selectFileBtn');
                var $templateRequiredTip = $modal.find('#templateRequiredTip');
                
                if ($selectFileBtn.length > 0) {
                    $selectFileBtn.prop('disabled', false).removeClass('layui-btn-disabled');
                    $templateRequiredTip.hide();
                    console.log('模板下载完成，文件选择按钮已启用');
                }
            });
            
            // 添加全局标记，表示模板已下载
            window.templateDownloaded = true;
                
            } catch (error) {
                // 关闭下载提示
                layui.layer.closeAll('loading');
                layui.layer.msg('下载失败，请检查网络连接或联系管理员', { icon: 2 });
                console.error('下载模板失败:', error);
            }
        }

        // 执行导入
        function executeImport() {
            console.log('执行导入函数被调用');
            
            var file = null;
            
            // 优先使用全局变量中的文件
            if (window.selectedImportFile) {
                file = window.selectedImportFile;
                console.log('使用全局变量中的文件:', file.name);
            } else {
                // 如果全局变量没有文件，尝试从DOM中查找
                console.log('全局变量中没有文件，尝试从DOM查找');
                
                var fileInput = null;
                var $fileInputs = $('.layui-layer-content:visible #importFile');
                
                console.log('查找到的文件输入框数量:', $fileInputs.length);
                
                if ($fileInputs.length > 0) {
                    fileInput = $fileInputs[0];
                } else {
                    // 如果在可见模态框中找不到，尝试在所有模态框中查找
                    fileInput = $('#importFile')[0];
                    console.log('在全局查找文件输入框:', fileInput ? '找到' : '未找到');
                }
                
                if (fileInput && fileInput.files && fileInput.files.length > 0) {
                    file = fileInput.files[0];
                    console.log('从DOM获取的文件:', file.name);
                }
            }
            
            // 检查是否有文件
            if (!file) {
                console.error('未找到要导入的文件 - 调试信息:', {
                    globalFile: !!window.selectedImportFile,
                    visibleModalCount: $('.layui-layer-content:visible').length,
                    totalFileInputs: $('#importFile').length
                });
                layui.layer.msg('请选择要导入的Excel文件', {icon: 2});
                return;
            }
            
            console.log('准备导入的文件信息:', {
                name: file.name,
                size: file.size,
                type: file.type
            });
            
            // 验证文件类型
            if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
                layui.layer.msg('请选择Excel文件(.xlsx或.xls)', { icon: 2 });
                return;
            }

            // 显示导入中提示
            layui.layer.msg('正在导入数据...', { icon: 16, time: 0 });

            var formData = new FormData();
            formData.append('file', file);

            // 获取WriteApiUrl配置
            var writeApiUrl = '@ViewData["WriteApiUrl"]' || 'http://localhost:5090/api';
            var url = writeApiUrl + '/Defective/Import';

            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    layui.layer.closeAll('loading');
                    if (response.code === 200) {
                        layui.layer.msg('导入成功: ' + response.msg, {icon: 1});
                        // 清除全局文件变量
                        window.selectedImportFile = null;
                        // 刷新数据
                        loadData();
                        // 关闭弹窗
                        layui.layer.closeAll();
                    } else {
                        layui.layer.msg('导入失败: ' + (response.msg || '未知错误'), { icon: 2 });
                    }
                },
                error: function () {
                    layui.layer.closeAll('loading');
                    layui.layer.msg('导入失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 导出数据
        function exportData() {
            // 获取搜索条件
            const defectiveCode = $('#defectiveCode').val() || '';
            const defectiveName = $('#defectiveName').val() || '';
            
            // 显示确认对话框
            let confirmMessage = '确定要导出不良品数据吗？';
            if (defectiveCode || defectiveName) {
                confirmMessage += '\n\n当前搜索条件：';
                if (defectiveCode) confirmMessage += '\n• 编号：' + defectiveCode;
                if (defectiveName) confirmMessage += '\n• 名称：' + defectiveName;
            }
            
            layui.layer.confirm(confirmMessage, {
                title: '确认导出',
                btn: ['确定导出', '取消'],
                icon: 3
            }, function(index) {
                // 用户确认导出
                layui.layer.close(index);
                
                // 显示加载提示
                const loadingIndex = layui.layer.load(1, {
                    shade: 0
                });
            
            // 构建查询参数
            const params = new URLSearchParams();
            if (defectiveCode) params.append('DefectiveCode', defectiveCode);
            if (defectiveName) params.append('DefectiveName', defectiveName);
            
            // 构建完整的API URL
            const apiUrl = '@ViewData["WriteApiUrl"]' + '/Defective/Export';
            const fullUrl = apiUrl + (params.toString() ? '?' + params.toString() : '');
            
            console.log('导出请求URL:', fullUrl);
            console.log('导出参数:', {
                DefectiveCode: defectiveCode,
                DefectiveName: defectiveName
            });
            
            // 使用fetch API下载文件
            fetch(fullUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/octet-stream'
                }
            })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401) {
                        throw new Error('需要登录认证，请先登录');
                    } else if (response.status === 403) {
                        throw new Error('没有权限执行此操作');
                    } else if (response.status === 404) {
                        throw new Error('导出接口不存在');
                    } else if (response.status === 500) {
                        throw new Error('服务器内部错误');
                    } else {
                        throw new Error(`请求失败，状态码: ${response.status}`);
                    }
                }
                
                // 检查响应类型
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
                    console.warn('响应类型不是Excel文件:', contentType);
                }
                
                return response.blob();
            })
            .then(blob => {
                // 检查文件大小
                if (blob.size === 0) {
                    throw new Error('导出的文件为空');
                }
                
                console.log('导出文件大小:', blob.size, 'bytes');
                
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const downloadLink = document.createElement('a');
                downloadLink.href = url;
                
                // 生成文件名，包含搜索条件
                let fileName = '不良品数据导出';
                if (defectiveCode) fileName += '_编号' + defectiveCode;
                if (defectiveName) fileName += '_名称' + defectiveName;
                fileName += '_' + new Date().toISOString().slice(0,19).replace(/[-T:]/g, '') + '.xlsx';
                
                downloadLink.download = fileName;
                
                // 触发下载
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
                
                // 清理URL对象
                window.URL.revokeObjectURL(url);
                
                // 关闭加载提示
                layui.layer.close(loadingIndex);
                
                // 显示成功提示
                layui.layer.msg('导出成功，文件已下载', {icon: 1, time: 2000});
                
                // 在控制台输出详细信息
                console.log('导出成功:', {
                    fileName: fileName,
                    fileSize: blob.size,
                    searchParams: {
                        DefectiveCode: defectiveCode,
                        DefectiveName: defectiveName
                    }
                });
            })
            .catch(error => {
                console.error('导出失败:', error);
                
                // 关闭加载提示
                layui.layer.close(loadingIndex);
                
                // 显示错误提示
                layui.layer.msg('导出失败: ' + error.message, {icon: 2, time: 3000});
                
                // 在控制台输出详细错误信息
                console.error('导出失败详情:', {
                    error: error,
                    url: fullUrl,
                    searchParams: {
                        DefectiveCode: defectiveCode,
                        DefectiveName: defectiveName
                    }
                });
            });
            });
        }

        // 处理导入文件选择
        function handleImportFileSelect(input) {
            console.log('文件选择事件触发');
            
            // 多种方式查找模态框中的元素
            var $modal = $(input).closest('.layui-layer-content');
            if ($modal.length === 0) {
                // 如果找不到layui-layer-content，尝试查找父级容器
                $modal = $(input).closest('.layui-layer');
                if ($modal.length === 0) {
                    // 最后尝试在当前可见的模态框中查找
                    $modal = $('.layui-layer-content:visible').last();
                }
            }
            
            console.log('找到模态框:', $modal.length);
            
            // 查找元素
            var $selectFileBtn = $modal.find('#selectFileBtn');
            var $fileNameText = $modal.find('#fileNameText');
            var $selectedFileName = $modal.find('#selectedFileName');
            var $importBtn = $modal.find('#importBtn');
            
            console.log('元素查找结果:', {
                selectFileBtn: $selectFileBtn.length,
                fileNameText: $fileNameText.length,
                selectedFileName: $selectedFileName.length,
                importBtn: $importBtn.length
            });
            
            // 检查是否已下载模板（优先检查全局标记）
            if (!window.templateDownloaded && $selectFileBtn.length > 0 && $selectFileBtn.prop('disabled')) {
                layui.layer.msg('请先下载模板文件', {icon: 2});
                return;
            }

            if (input.files && input.files.length > 0) {
                const file = input.files[0];
                console.log('选择的文件:', file.name);
                
                // 验证文件类型
                if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
                    layui.layer.msg('请选择Excel文件(.xlsx或.xls)', { icon: 2 });
                    input.value = '';
                    return;
                }

                // 验证文件大小（限制为10MB）
                if (file.size > 10 * 1024 * 1024) {
                    layui.layer.msg('文件大小不能超过10MB', { icon: 2 });
                    input.value = '';
                    return;
                }
                
                // 保存文件到全局变量
                window.selectedImportFile = file;
                console.log('文件已保存到全局变量:', file.name);
                
                // 显示文件名
                if ($fileNameText.length > 0) {
                    $fileNameText.text(file.name);
                    $selectedFileName.show();
                    console.log('文件名已设置');
                }
                
                // 启用导入按钮
                if ($importBtn.length > 0) {
                    $importBtn.prop('disabled', false).removeClass('layui-btn-disabled');
                    console.log('导入按钮已启用:', !$importBtn.prop('disabled'));
                } else {
                    console.error('未找到导入按钮，尝试全局查找');
                    // 尝试全局查找
                    $('.layui-layer-content:visible #importBtn').prop('disabled', false).removeClass('layui-btn-disabled');
                }
                
                layui.layer.msg('文件选择成功: ' + file.name, {icon: 1});
                
                // 额外的备用方案：延迟启用导入按钮
                setTimeout(function() {
                    enableImportButton();
                }, 100);
            }
        }
        
        // 备用函数：强制启用导入按钮
        function enableImportButton() {
            // 在所有可见模态框中查找导入按钮并启用
            var $importBtns = $('.layui-layer-content:visible #importBtn');
            $importBtns.each(function() {
                var $btn = $(this);
                $btn.prop('disabled', false)
                    .removeClass('layui-btn-disabled')
                    .attr('disabled', false)
                    .css({
                        'pointer-events': 'auto',
                        'opacity': '1',
                        'cursor': 'pointer'
                    });
                console.log('备用方案：导入按钮已强制启用', {
                    disabled: $btn.prop('disabled'),
                    hasDisabledClass: $btn.hasClass('layui-btn-disabled'),
                    pointerEvents: $btn.css('pointer-events')
                });
            });
        }
        
        // 调试函数：检查导入模态框状态
        window.debugImportModal = function() {
            console.log('=== 导入模态框调试信息 ===');
            console.log('模板已下载:', window.templateDownloaded);
            console.log('全局文件变量:', {
                hasGlobalFile: !!window.selectedImportFile,
                fileName: window.selectedImportFile ? window.selectedImportFile.name : '无文件'
            });
            
            var $modal = $('.layui-layer-content:visible').last();
            console.log('可见模态框数量:', $('.layui-layer-content:visible').length);
            
            if ($modal.length > 0) {
                var $selectFileBtn = $modal.find('#selectFileBtn');
                var $importBtn = $modal.find('#importBtn');
                var $importFile = $modal.find('#importFile');
                
                console.log('选择文件按钮状态:', {
                    exists: $selectFileBtn.length > 0,
                    disabled: $selectFileBtn.prop('disabled'),
                    hasDisabledClass: $selectFileBtn.hasClass('layui-btn-disabled'),
                    pointerEvents: $selectFileBtn.css('pointer-events')
                });
                
                console.log('导入按钮状态:', {
                    exists: $importBtn.length > 0,
                    disabled: $importBtn.prop('disabled'),
                    hasDisabledClass: $importBtn.hasClass('layui-btn-disabled'),
                    pointerEvents: $importBtn.css('pointer-events')
                });
                
                console.log('DOM文件选择状态:', {
                    hasFile: $importFile.length > 0 && $importFile[0].files && $importFile[0].files.length > 0,
                    fileName: $importFile.length > 0 && $importFile[0].files && $importFile[0].files.length > 0 ? $importFile[0].files[0].name : '无文件'
                });
            } else {
                console.log('未找到导入模态框');
            }
            console.log('========================');
        };

        // 显示视图设置
        function showViewSettings() {
            // TODO: 实现视图设置功能
            layui.layer.msg('视图设置功能待实现', { icon: 1 });
        }

        // 显示列设置
        function showColumnSettings() {
            // 显示列设置模态框
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '设置',
                    content: $('#columnSettingsModal'),
                    area: ['600px', '600px'],
                    shade: 0,
                    success: function(layero, index) {
                        // 以当前弹窗作为作用域，避免首次渲染到隐藏模板上
                        var $modal = $(layero);
                        initColumnSettings($modal);
                        initDragAndDrop($modal);
                        // 保险：显式绑定当前作用域内按钮点击事件
                        $modal.find('#btnColumnConfirm').off('click').on('click', function(){ confirmColumnSettings(); });
                        $modal.find('#btnColumnCancel').off('click').on('click', function(){ cancelColumnSettings(); });
                        $modal.find('#btnColumnReset').off('click').on('click', function(){ resetColumnSettings(); });
                    }
                });
            });
        }

        // 初始化列设置（作用域传入）
        function initColumnSettings($scope) {
            const columns = [
                { id: 'select', name: '选择', visible: true, order: 1 },
                { id: 'defectiveCode', name: '不良品项编号', visible: true, order: 2 },
                { id: 'defectiveName', name: '不良品项名称', visible: true, order: 3 },
                { id: 'attachment', name: '附件', visible: true, order: 4 },
                { id: 'image', name: '图片', visible: true, order: 5 },
                { id: 'createTime', name: '创建时间', visible: true, order: 6 },
                { id: 'creator', name: '创建人', visible: true, order: 7 },
                { id: 'modifier', name: '修改人', visible: true, order: 8 }
            ];

            // 按顺序排序
            columns.sort((a, b) => a.order - b.order);

            // 渲染列设置表格
            renderColumnSettingsTable(columns, $scope);
        }

        // 渲染列设置表格（作用域传入）
        function renderColumnSettingsTable(columns, $scope) {
            const tbody = ($scope ? $scope.find('#columnSettingsBody') : $('#columnSettingsBody'));
            tbody.empty();

            columns.forEach((col, index) => {
                const row = `
                    <tr data-column-id="${col.id}" data-order="${col.order}" draggable="true">
                        <td>${index + 1}</td>
                        <td class="column-name" style="cursor: move; user-select:none;">
                            <i class="layui-icon layui-icon-drag"></i> ${col.name}
                        </td>
                        <td>
                            <input type="checkbox" class="layui-checkbox" lay-skin="primary" 
                                   ${col.visible ? 'checked' : ''} 
                                   onchange="toggleColumnVisibility('${col.id}', this.checked)">
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });

            // 重新渲染Layui组件
            layui.form.render();
        }

        // 初始化拖拽功能（作用域传入）
        function initDragAndDrop($scope) {
            const $tbody = ($scope ? $scope.find('#columnSettingsBody') : $('#columnSettingsBody'));

            // jQuery UI
            if (typeof $.fn.sortable !== 'undefined') {
                $tbody.sortable({
                    handle: '.column-name',
                    axis: 'y',
                    update: function() { updateColumnOrder($scope); }
                });
                return;
            }

            // 原生 HTML5 拖拽
            let dragEl = null;
            $tbody.find('tr').each(function() {
                const $row = $(this);
                this.addEventListener('dragstart', function() { dragEl = this; this.classList.add('dragging'); });
                this.addEventListener('dragend', function() { this.classList.remove('dragging'); updateColumnOrder($scope); });
                this.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    const after = getDragAfterElement($tbody[0], e.clientY);
                    if (!after) $tbody[0].appendChild(dragEl);
                    else $tbody[0].insertBefore(dragEl, after);
                });
            });

            function getDragAfterElement(container, y) {
                const els = [...container.querySelectorAll('tr:not(.dragging)')];
                return els.reduce((closest, child) => {
                    const box = child.getBoundingClientRect();
                    const offset = y - box.top - box.height / 2;
                    if (offset < 0 && offset > closest.offset) return { offset: offset, element: child };
                    else return closest;
                }, { offset: Number.NEGATIVE_INFINITY }).element;
            }
        }

        // 更新列顺序（作用域传入）
        function updateColumnOrder($scope) {
            const $tbody = ($scope ? $scope.find('#columnSettingsBody') : $('#columnSettingsBody'));
            $tbody.find('tr').each(function(index) {
                $(this).data('order', index + 1);
                $(this).find('td:first').text(index + 1);
            });
        }

        // 重置列设置
        function resetColumnSettings() {
            // 重置为默认设置
            initColumnSettings($('.layui-layer-content:visible').last());
            layui.layer.msg('已重置为默认设置');
        }

        // 确认列设置（读取当前弹窗作用域）
        function confirmColumnSettings() {
            const $scope = $('.layui-layer-content:visible').last();
            const columns = [];
            $scope.find('#columnSettingsBody tr').each(function(index) {
                const columnId = $(this).data('column-id');
                const visible = $(this).find('input[type="checkbox"]').prop('checked');
                const order = index + 1;
                columns.push({ id: columnId, visible: visible, order: order });
            });

            applyColumnSettings(columns);
            layui.layer.msg('设置已保存并应用');
            // 只关闭当前设置弹窗
            const $layer = $scope.parents('.layui-layer');
            const idx = $layer.attr('times');
            if (idx) {
                layui.layer.close(idx);
            } else {
                layui.layer.closeAll();
            }
        }

        // 应用列设置到表格（含显示与顺序）
        function applyColumnSettings(columns) {
            // 先处理显示隐藏
            columns.forEach(col => {
                const columnIndex = getColumnIndex(col.id);
                if (columnIndex !== -1) {
                    if (col.visible) {
                        $(`#defectiveTable thead th:eq(${columnIndex})`).show();
                        $(`#defectiveTable tbody tr`).each(function() { $(this).find(`td:eq(${columnIndex})`).show(); });
                    } else {
                        $(`#defectiveTable thead th:eq(${columnIndex})`).hide();
                        $(`#defectiveTable tbody tr`).each(function() { $(this).find(`td:eq(${columnIndex})`).hide(); });
                    }
                }
            });

            // 再处理顺序（根据 order 重新排列DOM）
            reorderTable(columns);

            // 重新调整列宽
            adjustTableColumnWidths();
        }

        // 根据列顺序重排表头与每一行
        function reorderTable(columns) {
            const orderIds = columns
                .filter(c => c.visible) // 只对可见列排序
                .sort((a,b)=>a.order-b.order)
                .map(c => c.id);

            const idToIndex = {
                'select': 0,
                'defectiveCode': 1,
                'defectiveName': 2,
                'attachment': 3,
                'image': 4,
                'createTime': 5,
                'creator': 6,
                'modifier': 7
            };

            // 生成需要的索引顺序
            const newIndexOrder = orderIds.map(id => idToIndex[id]).filter(i => i !== undefined);

            // 重排表头
            const $theadRow = $('#defectiveTable thead tr');
            const ths = $theadRow.children('th').toArray();
            const fixedHidden = []; // 不可见列保持在原位隐藏
            // 先清空，再按顺序附加可见列，最后附加隐藏列
            $theadRow.empty();
            newIndexOrder.forEach(i => $theadRow.append(ths[i]));
            ths.forEach((th,i)=>{ if (!newIndexOrder.includes(i)) fixedHidden.push(th); });
            fixedHidden.forEach(th => $theadRow.append(th));

            // 重排每一行
            $('#defectiveTableBody tr').each(function(){
                const tds = $(this).children('td').toArray();
                const cellsHidden = [];
                const $row = $(this);
                $row.empty();
                newIndexOrder.forEach(i => $row.append(tds[i]));
                tds.forEach((td,i)=>{ if (!newIndexOrder.includes(i)) cellsHidden.push(td); });
                cellsHidden.forEach(td => $row.append(td));
            });
        }

        // 切换列显示/隐藏
        function toggleColumnVisibility(columnId, visible) {
            // 这里可以添加实时预览功能
            console.log(`列 ${columnId} 显示状态: ${visible}`);
        }

        // 更新选中项显示
        function updateSelectedItems() {
            // 收集选中的项目
            selectedItems = [];
            $('#defectiveTableBody tr input[type="checkbox"]:checked').each(function () {
                selectedItems.push(parseInt($(this).val()));
            });

            const count = selectedItems.length;
            $('#selectedCount').text(count);

            // 更新按钮状态
            const hasSelection = selectedItems.length > 0;

            // 强制更新按钮状态，确保样式一致
            if (hasSelection) {
                $('#editBtn').prop('disabled', false).removeClass('layui-btn-disabled');
                $('#deleteBtn').prop('disabled', false).removeClass('layui-btn-disabled');
                // 有选中时隐藏提示
                $('#selectionHint').hide();
            } else {
                $('#editBtn').prop('disabled', true).addClass('layui-btn-disabled');
                $('#deleteBtn').prop('disabled', true).addClass('layui-btn-disabled');
                // 无选中时显示提示
                $('#selectionHint').show();
            }

            // 更新全选复选框状态
            const totalRows = $('#defectiveTableBody tr').length;
            const checkedRows = $('#defectiveTableBody tr input:checked').length;

            if (totalRows > 0 && checkedRows === totalRows) {
                $('#selectAll').prop('checked', true);
            } else {
                $('#selectAll').prop('checked', false);
            }

            // 调试信息（可选，生产环境可以注释掉）
            console.log('按钮状态更新:', {
                selectedItems: selectedItems,
                hasSelection: hasSelection,
                editBtnDisabled: $('#editBtn').prop('disabled'),
                deleteBtnDisabled: $('#deleteBtn').prop('disabled')
            });
        }

        // 全选/取消全选
        function toggleSelectAll() {
            const isChecked = $('#selectAll').prop('checked');
            $('#defectiveTableBody tr input[type="checkbox"]').prop('checked', isChecked);

            // 更新选中项
            if (isChecked) {
                // 全选
                selectedItems = [];
                $('#defectiveTableBody tr input[type="checkbox"]').each(function () {
                    selectedItems.push(parseInt($(this).val()));
                });
            } else {
                // 取消全选
                selectedItems = [];
            }

            updateSelectedItems();
        }

        // 排序表格
        function sortTable(column) {
            // TODO: 实现排序功能
            alert('排序功能待实现，列: ' + column);
        }

        // 下载附件
        function downloadAttachment(filename) {
            // TODO: 实现附件下载功能
            alert('附件下载功能待实现: ' + filename);
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN');
        }

        // 图片上传相关函数
        function triggerImageUpload() {
            const $scope = getAddModalContext();
            $scope.find('#addImageFile').click();
        }

        function handleImageSelect(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                console.log('Selected file:', file);
                console.log('File type:', file.type);
                console.log('File size:', file.size);

                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    layui.layer.msg('请选择图片文件', { icon: 2 });
                    return;
                }

                // 验证文件大小（限制为5MB）
                if (file.size > 5 * 1024 * 1024) {
                    layui.layer.msg('图片大小不能超过5MB', { icon: 2 });
                    return;
                }

                // 显示加载提示
                const loadingIndex = layui.layer.load(1, {
                    shade: 0
                });

                // 上传图片到后端
                uploadImageToServer(file, loadingIndex);
            }
        }

        // 上传图片到服务器
        function uploadImageToServer(file, loadingIndex) {
            const formData = new FormData();
            formData.append('file', file);

            // 获取WriteApiUrl配置
            const uploadUrl = WRITE_API_URL + '/Img/UploadImg';

            $.ajax({
                url: uploadUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    if (loadingIndex) {
                        layui.layer.close(loadingIndex);
                    }
                    console.log('Upload response:', response);
                    console.log('Response type:', typeof response);

                    if (response && response.code === 200) {
                        // 上传成功，显示图片预览
                        const imageUrl = normalizeImageUrl(response.data || response);
                        console.log('Image URL from response.data:', imageUrl);
                        showImagePreview(imageUrl);

                        // 保存图片URL到隐藏字段，用于提交表单
                        $('#addImageUrl').val(imageUrl);

                        layui.layer.msg('图片上传成功', { icon: 1 });
                    } else {
                        // 如果返回的是直接的URL字符串
                        if (typeof response === 'string') {
                            const normalized = normalizeImageUrl(response);
                            console.log('Direct URL response:', response, '->', normalized);
                            showImagePreview(normalized);
                            $('#addImageUrl').val(normalized);
                            layui.layer.msg('图片上传成功', { icon: 1 });
                        } else {
                            console.log('Upload failed response:', response);
                            layui.layer.msg('图片上传失败: ' + (response.msg || '未知错误'), { icon: 2 });
                        }
                    }
                },
                error: function (xhr, status, error) {
                    if (loadingIndex) {
                        layui.layer.close(loadingIndex);
                    }
                    console.error('图片上传失败:', error);
                    layui.layer.msg('图片上传失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        function showImagePreview(imageSrc) {
            const $scope = getAddModalContext();
            console.log('showImagePreview called with:', imageSrc);
            console.log('imagePreview element:', $scope.find('#imagePreview'));
            console.log('imagePreview img element:', $scope.find('#imagePreview img'));
            $scope.find('#imagePreview img').attr('src', imageSrc);
            $scope.find('#imagePreview').show();
            $scope.find('#imagePlaceholder').hide();
            console.log('After showImagePreview:');
            console.log('imagePreview display:', $scope.find('#imagePreview').css('display'));
            console.log('imagePlaceholder display:', $scope.find('#imagePlaceholder').css('display'));
            console.log('img src:', $scope.find('#imagePreview img').attr('src'));
        }

        function removeImage() {
            const $scope = getAddModalContext();
            $scope.find('#addImageFile').val('');
            $scope.find('#addImageUrl').val('');
            $scope.find('#imagePreview').hide();
            $scope.find('#imagePlaceholder').show();
        }

        // 附件上传相关函数
        function triggerAttachmentUpload() {
            const $scope = getAddModalContext();
            $scope.find('#addAttachmentFile').click();
        }

        function handleAttachmentSelect(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];

                // 验证文件类型
                const allowedTypes = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt', '.zip', '.rar'];
                const lowerCaseFileName = file.name.toLowerCase();
                const isAllowed = allowedTypes.some(type => lowerCaseFileName.endsWith(type));

                if (!isAllowed) {
                    layui.layer.msg('请选择PDF、Word、Excel、TXT或压缩包文件', {icon: 2});
                    return;
                }

                // 验证文件大小（限制为10MB）
                if (file.size > 10 * 1024 * 1024) {
                    layui.layer.msg('文件大小不能超过10MB', { icon: 2 });
                    return;
                }
                
                // 显示上传中提示
                const loadingIndex = layui.layer.load(1, { shade: 0 });
                
                // 上传附件到后端
                uploadAttachmentToServer(file, loadingIndex);
            }
        }

        // 将附件上传到服务器（/Img/UploadFile）
        function uploadAttachmentToServer(file, loadingIndex) {
            const formData = new FormData();
            formData.append('file', file);
            const uploadUrl = WRITE_API_URL + '/Img/UploadFile';
            $.ajax({
                url: uploadUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    if (loadingIndex) layui.layer.close(loadingIndex);
                    if (res && res.code === 200 && res.data) {
                        // 保存返回的URL到隐藏字段
                        const url = res.data.fileUrl || res.data.filePath || '';
                        $('#addAttachmentUrl').val(url);
                        showAttachmentPreview('');
                        layui.layer.msg('附件上传成功', {icon: 1});
                    } else {
                        layui.layer.msg('附件上传失败: ' + (res.msg || '未知错误'), {icon: 2});
                    }
                },
                error: function() {
                    if (loadingIndex) layui.layer.close(loadingIndex);
                    layui.layer.msg('附件上传失败，请检查网络连接', {icon: 2});
                }
            });
        }

        function showAttachmentPreview(fileSrc) {
            const $scope = getAddModalContext();
            const fileName = $scope.find('#addAttachmentFile')[0] ? ($scope.find('#addAttachmentFile')[0].files[0] ? $scope.find('#addAttachmentFile')[0].files[0].name : '') : '';
            $scope.find('#attachmentPreview .layui-upload-file-info .file-name').text(fileName);
            $scope.find('#attachmentPreview').show();
            $scope.find('#attachmentPlaceholder').hide();
        }

        function removeAttachment() {
            const $scope = getAddModalContext();
            $scope.find('#addAttachmentFile').val('');
            $scope.find('#attachmentPreview').hide();
            $scope.find('#attachmentPlaceholder').show();
        }

        // 初始化拖拽上传
        function initImageDragAndDrop() {
            // 初始化图片拖拽上传
            const imageUploadArea = document.querySelector('.layui-upload-area:not(.attachment-area)');
            if (imageUploadArea) {
                initDragAndDropForArea(imageUploadArea, 'image');
            }

            // 初始化附件拖拽上传
            const attachmentUploadArea = document.querySelector('.attachment-area');
            if (attachmentUploadArea) {
                initDragAndDropForArea(attachmentUploadArea, 'attachment');
            }
        }

        function initDragAndDropForArea(uploadArea, type) {
            if (!uploadArea) return;

            uploadArea.addEventListener('dragover', function (e) {
                e.preventDefault();
                this.classList.add('dragover');
            });

            uploadArea.addEventListener('dragleave', function (e) {
                e.preventDefault();
                this.classList.remove('dragover');
            });

            uploadArea.addEventListener('drop', function (e) {
                e.preventDefault();
                this.classList.remove('dragover');

                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    const file = files[0];

                    if (type === 'image') {
                        if (file.type.startsWith('image/')) {
                            // 验证文件大小
                            if (file.size > 5 * 1024 * 1024) {
                                layui.layer.msg('图片大小不能超过5MB', { icon: 2 });
                                return;
                            }

                            // 设置文件到input
                            const input = document.getElementById('addImageFile');
                            input.files = files;

                            // 创建预览
                            const reader = new FileReader();
                            reader.onload = function (e) {
                                showImagePreview(e.target.result);
                            };
                            reader.readAsDataURL(file);
                        } else {
                            layui.layer.msg('请拖拽图片文件', { icon: 2 });
                        }
                    } else if (type === 'attachment') {
                        // 验证文件类型
                        const allowedTypes = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt', '.zip', '.rar'];
                        const lowerCaseFileName = file.name.toLowerCase();
                        const isAllowed = allowedTypes.some(type => lowerCaseFileName.endsWith(type));

                        if (isAllowed) {
                            // 验证文件大小
                            if (file.size > 10 * 1024 * 1024) {
                                layui.layer.msg('文件大小不能超过10MB', { icon: 2 });
                                return;
                            }

                            // 设置文件到input
                            const input = document.getElementById('addAttachmentFile');
                            input.files = files;

                            // 创建预览
                            const reader = new FileReader();
                            reader.onload = function (e) {
                                showAttachmentPreview(e.target.result);
                            };
                            reader.readAsDataURL(file);
                        } else {
                            layui.layer.msg('请拖拽PDF、Word、Excel、TXT或压缩包文件', {icon: 2});
                        }
                    }
                }
            });
        }

        // 显示编辑模态框
        function showEditModal(rowData) {
            // 先清理模板区，避免误操作隐藏模板中的元素
            (function(){
                const $tpl = $('#editDefectiveModal');
                $tpl.find('#editAttachmentPreview').hide();
                $tpl.find('#editAttachmentPlaceholder').show();
                $tpl.find('#editImagePreview').hide();
                $tpl.find('#editImagePlaceholder').show();
            })();
            
            // 显示编辑模态框
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '编辑不良品',
                    content: $('#editDefectiveModal').html(),
                    area: ['500px', '450px'], // 减少高度
                    shade: 0,
                    btn: ['保存', '重置', '取消'],
                    btn1: function (index, layero) {
                        saveEditDefective(index);
                    },
                    btn2: function (index, layero) {
                        resetEditForm();
                    },
                    btn3: function (index, layero) {
                        layer.close(index);
                    },
                    success: function(layero, index) {
                        // 重新填充数据（定位到当前弹窗内的元素）
                        const $scope = getEditModalContext();
                        $scope.find('#editDefectiveId').val(rowData.id);
                        $scope.find('#editDefectiveCode').val(rowData.defectiveCode);
                        $scope.find('#editDefectiveName').val(rowData.defectiveName);
                        
                        // 处理附件预览
                        if (rowData.attachmentPath) {
                            $scope.find('#editAttachmentPreview .file-name').text(rowData.attachmentPath);
                            $scope.find('#editAttachmentPreview').show();
                            $scope.find('#editAttachmentPlaceholder').hide();
                        } else {
                            $scope.find('#editAttachmentPreview').hide();
                            $scope.find('#editAttachmentPlaceholder').show();
                        }

                        // 处理图片预览
                        if (rowData.imagePath) {
                            $scope.find('#editImagePreview img').attr('src', rowData.imagePath);
                            $scope.find('#editImagePreview').show();
                            $scope.find('#editImagePlaceholder').hide();
                            $scope.find('#editImageUrl').val(rowData.imagePath); // 设置图片URL到隐藏字段
                        } else {
                            $scope.find('#editImagePreview').hide();
                            $scope.find('#editImagePlaceholder').show();
                            $scope.find('#editImageUrl').val(''); // 清空图片URL
                        }

                        // 重新绑定删除按钮事件
                        bindEditModalEvents();

                        // 重新渲染表单
                        layui.form.render();
                    }
                });
            });
        }

        // 保存编辑的不良品
        function saveEditDefective(layerIndex) {
            // 获取表单数据（限定在当前编辑弹窗作用域）
            const $scope = getEditModalContext();
            const defectiveId = $scope.find('#editDefectiveId').val();
            const defectiveCode = $scope.find('#editDefectiveCode').val().trim();
            const defectiveName = $scope.find('#editDefectiveName').val().trim();
            const attachmentFile = $scope.find('#editAttachmentFile')[0] ? $scope.find('#editAttachmentFile')[0].files[0] : null;
            const imageUrl = $scope.find('#editImageUrl').val(); // 获取图片URL

            // 验证必填字段
            if (!defectiveCode) {
                layui.layer.msg('请输入不良品项编号', { icon: 2 });
                return;
            }
            if (!defectiveName) {
                layui.layer.msg('请输入不良品项名称', { icon: 2 });
                return;
            }

            // 创建FormData对象用于文件上传
            const formData = new FormData();
            formData.append('id', defectiveId);
            formData.append('defectiveCode', defectiveCode);
            formData.append('defectiveName', defectiveName);

            // 处理附件文件
            if (attachmentFile) {
                formData.append('attachmentFile', attachmentFile);
            }

            // 处理图片URL
            if (imageUrl) {
                formData.append('imagePath', imageUrl);
            }

            // 发送PUT请求到WriteApiUrl
            $.ajax({
                url: '@Url.Action("Update", "Defective")',
                type: 'POST', // 使用POST模拟PUT，因为HTML表单不支持PUT
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    if (response.code === 200) {
                        layui.layer.msg('编辑成功', { icon: 1 });
                        layui.layer.close(layerIndex);

                        // 重新加载数据
                        loadData();

                        // 清空选中项
                        selectedItems = [];
                        updateSelectedItems();
                    } else {
                        layui.layer.msg('编辑失败: ' + (response.msg || '未知错误'), { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    console.error('编辑请求失败:', error);
                    layui.layer.msg('编辑失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 重置编辑表单
        function resetEditForm() {
            const $scope = getEditModalContext();
            if ($scope.find('#editDefectiveForm')[0]) $scope.find('#editDefectiveForm')[0].reset();
            $scope.find('#editImageUrl').val(''); // 清空图片URL
            $scope.find('#editAttachmentPreview').hide();
            $scope.find('#editAttachmentPlaceholder').show();
            $scope.find('#editImagePreview').hide();
            $scope.find('#editImagePlaceholder').show();
        }

        // 编辑模态框的附件上传相关函数
        function triggerEditAttachmentUpload() {
            const $scope = getEditModalContext();
            $scope.find('#editAttachmentFile').click();
        }

        function handleEditAttachmentSelect(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];

                // 验证文件类型
                const allowedTypes = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt'];
                const lowerCaseFileName = file.name.toLowerCase();
                const isAllowed = allowedTypes.some(type => lowerCaseFileName.endsWith(type));

                if (!isAllowed) {
                    layui.layer.msg('请选择PDF、Word、Excel或TXT文件', { icon: 2 });
                    return;
                }

                // 验证文件大小（限制为10MB）
                if (file.size > 10 * 1024 * 1024) {
                    layui.layer.msg('文件大小不能超过10MB', { icon: 2 });
                    return;
                }

                // 显示预览
                const $scope = getEditModalContext();
                $scope.find('#editAttachmentPreview .file-name').text(file.name);
                $scope.find('#editAttachmentPreview').show();
                $scope.find('#editAttachmentPlaceholder').hide();
            }
        }

        function removeEditAttachment() {
            const $scope = getEditModalContext();
            $scope.find('#editAttachmentFile').val('');
            $scope.find('#editAttachmentPreview').hide();
            $scope.find('#editAttachmentPlaceholder').show();
        }

        // 编辑模态框的图片上传相关函数
        function triggerEditImageUpload() {
            const $scope = getEditModalContext();
            $scope.find('#editImageFile').click();
        }

        function handleEditImageSelect(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];

                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    layui.layer.msg('请选择图片文件', { icon: 2 });
                    return;
                }

                // 验证文件大小（限制为5MB）
                if (file.size > 5 * 1024 * 1024) {
                    layui.layer.msg('图片大小不能超过5MB', { icon: 2 });
                    return;
                }

                // 显示上传中提示
                layui.layer.msg('正在上传图片...', { icon: 16, time: 0 });

                // 上传图片到后端
                uploadEditImageToServer(file);
            }
        }

        // 上传编辑模态框的图片到服务器
        function uploadEditImageToServer(file) {
            const formData = new FormData();
            formData.append('file', file);

            // 获取WriteApiUrl配置
            const uploadUrl = WRITE_API_URL + '/Img/UploadImg';

            $.ajax({
                url: uploadUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    layui.layer.closeAll('loading');

                    if (response && response.code === 200) {
                        // 上传成功，显示图片预览
                        const imageUrl = normalizeImageUrl(response.data || response);
                        const $scope = getEditModalContext();
                        $scope.find('#editImagePreview img').attr('src', imageUrl);
                        $scope.find('#editImagePreview').show();
                        $scope.find('#editImagePlaceholder').hide();
                        
                        // 保存图片URL到隐藏字段，用于提交表单
                        $scope.find('#editImageUrl').val(imageUrl);
                        
                        layui.layer.msg('图片上传成功', {icon: 1});
                    } else {
                        // 如果返回的是直接的URL字符串
                        if (typeof response === 'string') {
                            const normalized = normalizeImageUrl(response);
                            const $scope = getEditModalContext();
                            $scope.find('#editImagePreview img').attr('src', normalized);
                            $scope.find('#editImagePreview').show();
                            $scope.find('#editImagePlaceholder').hide();
                            $scope.find('#editImageUrl').val(normalized);
                            layui.layer.msg('图片上传成功', {icon: 1});
                        } else {
                            layui.layer.msg('图片上传失败: ' + (response.msg || '未知错误'), { icon: 2 });
                        }
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.closeAll('loading');
                    console.error('图片上传失败:', error);
                    layui.layer.msg('图片上传失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        function removeEditImage() {
            const $scope = getEditModalContext();
            $scope.find('#editImageFile').val('');
            $scope.find('#editImageUrl').val(''); // 清空图片URL
            $scope.find('#editImagePreview').hide();
            $scope.find('#editImagePlaceholder').show();
        }

        // 绑定新增模态框的事件
        function bindAddModalEvents() {
            const $scope = getAddModalContext();
            $scope.find('#attachmentPreview .layui-upload-remove').off('click').on('click', function () {
                removeAttachment();
            });
            $scope.find('#imagePreview .layui-remove').off('click').on('click', function () {
                removeImage();
            });
            $scope.find('#attachmentPlaceholder').off('click').on('click', function () {
                triggerAttachmentUpload();
            });
            $scope.find('#imagePlaceholder').off('click').on('click', function () {
                triggerImageUpload();
            });
            $scope.find('#addAttachmentFile').off('change').on('change', function () {
                handleAttachmentSelect(this);
            });
            $scope.find('#addImageFile').off('change').on('change', function () {
                handleImageSelect(this);
            });
        }

        // 绑定编辑模态框的事件
        function bindEditModalEvents() {
            const $scope = getEditModalContext();
            // 绑定附件删除按钮事件
            $scope.find('#editAttachmentPreview .layui-upload-remove').off('click').on('click', function() {
                removeEditAttachment();
            });

            // 绑定图片删除按钮事件
            $scope.find('#editImagePreview .layui-remove').off('click').on('click', function() {
                removeEditImage();
            });

            // 绑定附件上传区域点击事件
            $scope.find('#editAttachmentPlaceholder').off('click').on('click', function() {
                triggerEditAttachmentUpload();
            });

            // 绑定图片上传区域点击事件
            $scope.find('#editImagePlaceholder').off('click').on('click', function() {
                triggerEditImageUpload();
            });

            // 绑定文件选择事件
            $scope.find('#editAttachmentFile').off('change').on('change', function() {
                handleEditAttachmentSelect(this);
            });
            
            $scope.find('#editImageFile').off('change').on('change', function() {
                handleEditImageSelect(this);
            });
        }

        // 取消列设置（只关闭当前设置弹窗）
        function cancelColumnSettings() {
            var $modal = $('.layui-layer-content:visible').last();
            var $layer = $modal.parents('.layui-layer');
            var index = $layer.attr('times');
            if (index) {
                layui.layer.close(index);
            } else {
                layui.layer.closeAll();
            }
        }

        // 获取列索引（供显示/隐藏阶段使用）
        function getColumnIndex(columnId) {
            const columnMap = {
                'select': 0,
                'defectiveCode': 1,
                'defectiveName': 2,
                'attachment': 3,
                'image': 4,
                'createTime': 5,
                'creator': 6,
                'modifier': 7
            };
            return (columnMap.hasOwnProperty(columnId) ? columnMap[columnId] : -1);
        }
    </script>
}
